<?php

namespace app\wechat\controller\swoole;

// swoole客户端
class Client
{
    public $client;

    // 初始化
    public function __construct()
    {
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP);
    }

    // 连接swoole服务端
    public function connect()
    {
        if (!$this->client->connect("127.0.0.1", 9501)) {
            Log::error("connect failed");
            die("connect failed.");
        }
    }

    // 发送数据
    public function send($msg)
    {
        if ($msg) {
            if (!$this->client->send($msg)) {
                Log::error("send " . $msg . "failed");
                die("send msg failed.");
            }
        }
    }

    // 接受返回数据
    public function recv()
    {
        $data = $this->client->recv();
        if (!$data) {
            die("recv failed.");
        }
        return $data;
    }

    // 关闭连接
    public function close()
    {
        $this->client->close();
    }

}
